<?php

namespace App\Http\Servers\Home;

use App\Http\Repository\SetRepository;
use Illuminate\Support\Facades\Request;

class BaseServer
{
    private $setRepository;

    public function __construct(SetRepository $setRepository)
    {
        $this->setRepository = $setRepository;
    }

    //得到网站配置信息
    public function getConfig()
    {
        return $this->setRepository->getSet();
    }

    //得到碎片
    public function frame(Array $frames)
    {
        $tmpFrame[] = ['url' => route('index'), 'name' => config('app.home_name')];
        $frames = array_collapse([$tmpFrame, $frames]);
        return $frames;
    }

    //地区关键词处理
    public function keywordDowork($request, &$keyword)
    {
        $all = \Cache::get('share');
        if (empty($all['areaslist'])) {
            return false;
        }
        foreach ($all['areaslist'] as $group) {
            foreach ($group as $value) {
                $areaslist[] = $value['name'];
            }
        }

        if (!empty($request->area)) {
            $where['domain'] = $request->area;
        } elseif (!empty(config('set.web_default_area'))) {
            $where['id'] = config('set.web_default_area');
        } else {
            \Cache::forget('area');
        }
        if (!empty($where)) {
            $area = \App\Area::where($where)
                ->select('name', 'domain')
                ->get()
                ->toArray();
            if ($area) {
                $keyword = str_replace($areaslist, '', $keyword);
                $keyword = $area[0]['name'] . str_replace(',', ',' . $area[0]['name'], $keyword);
                \Cache::forever('area', $area[0]['domain']);
            }
        }
    }

    //得到rss 和 pushurl的超链接
    public function getUrl($explode = false)
    {
        $all = \Cache::get('share');
        $url = [];
        //得到企业信息
        foreach ($all['pages'] as $key => $label) {
            foreach ($label as $page) {
                if ($explode) {
                    $url['企业信息'][] = [
                        'title' => $page['name'],
                        'url' => route('page', [$key, $page['id']]),
                        'simpledescribe' => $page['simpledescribe'],
                        'time' => $page['time'],
                    ];
                } else {
                    $url[] = [
                        'title' => $page['name'],
                        'url' => route('page', [$key, $page['id']]),
                        'simpledescribe' => $page['simpledescribe'],
                        'time' => $page['time'],
                    ];
                }
            }
        }

        //得到地区名称数据 用于去除关键词中的地区
        if (!\Cache::has('allAreas')) {
            $allAreas = \App\Area::lists('name')->toArray();
            \Cache::forever('allAreas', $allAreas);
        } else {
            $allAreas = \Cache::get('allAreas');
        }

//        $areasId = explode(',', config('set.web_area'));
//        //去除重复项
//        $areasId = array_unique($areasId);
//
//        if (!empty($areasId)) {
//            foreach ($areasId as $id) {
//                $tmpWhere[] = 'path like "%,' . $id . ',%"';
//            }
//            $where = implode(' or ', $tmpWhere);
//        }
//        $areas = \App\Area::whereIn('id', $areasId)
//            ->orWhere(function ($query) use ($where) {
//                if (!empty($where)) {
//                    $query->whereRaw($where);
//                }
//            })
//            ->lists('name')
//            ->toArray();
        $areas = array_column(array_collapse(\Cache::get('share')['areaslist']), 'name');

        //得到搜索页面
        if (!empty(config('set.web_keywords'))) {
            foreach (explode(',', config('set.web_keywords')) as $keyword) {
                //原关键词
                if ($explode) {

                    $url['搜索页面'][] = [
                        'title' => $keyword,
                        'url' => route('search', $keyword),
                        'simpledescribe' => $keyword . '_' . config('set.web_name'),
                        'time' => $page['time'],
                    ];
                } else {
                    $url[] = [
                        'title' => $keyword,
                        'url' => route('search', $keyword),
                        'simpledescribe' => $keyword . '_' . config('set.web_name'),
                        'time' => $page['time'],
                    ];
                }
                foreach (explode(',', config('set.web_keywords_long')) as $long) {
                    //关键词长尾词
                    if ($explode) {
                        $url['搜索页面'][] = [
                            'title' => $keyword . $long,
                            'url' => route('search', $keyword . $long),
                            'simpledescribe' => $keyword . $long . '_' . config('set.web_name'),
                            'time' => $page['time'],
                        ];
                    } else {
                        $url[] = [
                            'title' => $keyword . $long,
                            'url' => route('search', $keyword . $long),
                            'simpledescribe' => $keyword . $long . '_' . config('set.web_name'),
                            'time' => $page['time'],
                        ];
                    }
                    foreach ($areas as $area) {
                        //去除关键词地区
                        $keyword = str_replace($allAreas, '', $keyword);
                        //地区关键词
                        if ($explode) {
                            $url['搜索页面'][] = [
                                'title' => $area . $keyword,
                                'url' => route('search', $area . $keyword),
                                'simpledescribe' => $area . $keyword . '_' . config('set.web_name'),
                                'time' => $page['time'],
                            ];
                        } else {
                            $url[] = [
                                'title' => $area . $keyword . '_' . config('set.web_name'),
                                'url' => route('search', $area . $keyword),
                                'simpledescribe' => $area . $keyword . '_' . config('set.web_name'),
                                'time' => $page['time'],
                            ];
                        }
                        //地区关键词长尾词
                        if ($explode) {
                            $url['搜索页面'][] = [
                                'title' => $area . $keyword . $long,
                                'url' => route('search', $area . $keyword . $long),
                                'simpledescribe' => $area . $keyword . $long . '_' . config('set.web_name'),
                                'time' => $page['time'],
                            ];
                        } else {
                            $url[] = [
                                'title' => $area . $keyword . $long . '_' . config('set.web_name'),
                                'url' => route('search', $area . $keyword . $long),
                                'simpledescribe' => $area . $keyword . $long . '_' . config('set.web_name'),
                                'time' => $page['time'],
                            ];
                        }
                    }
                }
            }
        }

        //得到企业分站
        foreach ($all['areaslist'] as $group) {
            foreach ($group as $area) {
                if ($explode) {
                    $url['企业分站'][] = [
                        'title' => config('set.web_name') . $area['name'] . '分站',
                        'url' => route('index_area', $area['domain']),
                        'simpledescribe' => $area['name'] . str_replace(',', ',' . $area['name'], config('set.web_keywords')),
                        'time' => date('Y-m-d H:i:s'),
                    ];
                } else {
                    $url[] = [
                        'title' => config('set.web_name') . $area['name'] . '分站',
                        'url' => route('index_area', $area['domain']),
                        'simpledescribe' => $area['name'] . str_replace(',', ',' . $area['name'], config('set.web_keywords')),
                        'time' => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        //得到分类
        foreach ($all['sorts'] as $chunk) {
            foreach ($chunk as $sort) {
                if ($explode) {
                    $url['分类信息'][] = [
                        'title' => $sort['name'],
                        'url' => route('sort', [$sort['chunk'], $sort['id']]),
                        'simpledescribe' => !empty($sort['simpledescribe']) ? $sort['simpledescribe'] : config('set.web_description'),
                        'time' => $sort['time'],
                    ];
                } else {
                    $url[] = [
                        'title' => $sort['name'],
                        'url' => route('sort', [$sort['chunk'], $sort['id']]),
                        'simpledescribe' => !empty($sort['simpledescribe']) ? $sort['simpledescribe'] : config('set.web_description'),
                        'time' => $sort['time'],
                    ];
                }
            }
        }

        //得到信息
        foreach ($all['allInfos'] as $chunk) {
            foreach ($chunk as $info) {
                if ($explode) {
                    $url['详细信息'][] = [
                        'title' => $info['name'],
                        'url' => route('info', [$info['chunk'], $info['id']]),
                        'simpledescribe' => !empty($info['simpledescribe']) ? $info['simpledescribe'] : config('set.web_description'),
                        'time' => $sort['time'],
                    ];
                } else {
                    $url[] = [
                        'title' => $info['name'],
                        'url' => route('info', [$info['chunk'], $info['id']]),
                        'simpledescribe' => !empty($info['simpledescribe']) ? $info['simpledescribe'] : config('set.web_description'),
                        'time' => $sort['time'],
                    ];
                }
            }
        }

        return $url;
    }

    //拼接长尾关键词
    public function getLongKeywords($tag)
    {
        $tags[] = $tag;
        foreach (explode(',', config('set.web_keywords_long')) as $long) {
            $tags[] = $tag . $long;
        }
        return implode(',', $tags);
    }

    //得到热门关键词
    public function getSeo($keyword, $num)
    {
        //得到关键词数据
        $tmpKeywordArray = explode(',', $keyword);
        //得到指定数量的关键词
        $keywordArray = array_chunk($tmpKeywordArray, $num);
        //得到seo标签
        $return = [];
        foreach ($keywordArray[0] as $value) {
            $return[] = '<a target="_blank" href="' . route('search', $value) . '" title="' . $value . '" alt="' . $value . '">' . $value . '</a>';
        }

        return implode(',', $return);
    }

    //得到access_token
    public static function getAccessToken()
    {
        if (!\Cache::has('access_token')) {
            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token');
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 0);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置get数据
            $get_data = array(
                "grant_type" => "client_credential",
                "appid" => config('app.wechatSet.appid'),
                "secret" => config('app.wechatSet.secret'),
            );
            curl_setopt($curl, CURLOPT_POSTFIELDS, $get_data);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            //执行命令
            $data = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);
            //显示获得的数据
            $tokeninfo = json_decode($data, true);
            @$access_token = $tokeninfo['access_token'];
            @\Cache::put('access_token', $tokeninfo['access_token'], 60);
        } else {
            @$access_token = \Cache::get('access_token');
        }

        return $access_token;
    }

    //发送在线留言通知信息到微信公众号
    public function sendWechatMsg($request)
    {
        $accessToken = self::getAccessToken();
        //信息模版
        $template_id = config('app.wechatSet.template_id.sendWechatMsg');
        //发送用户
        $toUsers = config('app.wechatSet.openid');
        //查看网址
        $url = route('admin.auth.getlogin');
        //信息颜色
        $color = config('app.wechatSet.color');
        //准备数据
        $data = [
            'first' => [
                'value' => config('set.web_name'),
                'color' => $color,
            ],
            'keyword1' => [
                'value' => $request->msg_name,
                'color' => $color,
            ],
            'keyword2' => [
                'value' => $request->phone,
                'color' => $color,
            ],
            'keyword3' => [
                'value' => date('Y-m-d H:i:s'),
                'color' => $color,
            ],
            'remark' => [
                'value' => '点击查看详情',
                'color' => $color,
            ]
        ];

        foreach ($toUsers as $toUser) {
            $sendData['touser'] = $toUser;
            $sendData['template_id'] = $template_id;
            $sendData['url'] = $url;
            $sendData['data'] = $data;

            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 0);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($sendData));
            //执行命令
            $info = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);
        }
    }


}